#include "bgmlist.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

BGMList::BGMList(QObject *parent)
    : QObject{parent}
{
    QString resoucePath=":/music/";

    QDir dir(resoucePath);

    qDebug()<<dir.entryList();

    if(!dir.exists()){
        qDebug()<<"资源路径不存在";
        return;
    }
    qDebug()<<resoucePath;

    QStringList filters;
    filters<<"*.mp3";
    QStringList files=dir.entryList(filters,QDir::Files);

    QJsonObject root;
    QJsonArray manList;
    QJsonArray womanList;
    QJsonArray bgmList;
    QJsonArray endingList;
    QJsonArray otherList;

    for(QString& file:files){
        QString filePath=resoucePath+file;

        if(file.startsWith("Man_")){//startsWith是用于检查字符串是否以指定的前缀开头
            manList.append(filePath);
        }else if(file.startsWith("Woman_")){
            womanList.append(filePath);
        }else if(file.startsWith("MusicEx_")){
            if(file.contains("Win")||file.contains("Lose")){
                endingList.append(filePath);
            }else{
                bgmList.append(filePath);
            }
        }else{
            otherList.append(filePath);
        }
    }



    root["Man"]=manList;
    root["Woman"]=womanList;
    root["BGM"]=bgmList;
    root["Ending"]=endingList;
    root["Other"]=otherList;
    // QJsonObject manObject;
    // manObject.insert("Man", manList);
    // rootArray.append(manObject);

    // QJsonObject womanObject;
    // womanObject.insert("Woman", womanList);
    // rootArray.append(womanObject);

    // QJsonObject bgmObject;
    // bgmObject.insert("BGM", bgmList);
    // rootArray.append(bgmObject);

    // QJsonObject endingObject;
    // endingObject.insert("Ending", endingList);
    // rootArray.append(endingObject);

    // QJsonObject otherObject;
    // otherObject.insert("Other", otherList);
    // rootArray.append(otherObject);



    QJsonDocument doc(root);

    QString projectRootPath=getProjectRootPath()+"/resource/conf/PlayList.json";

    QFile jsonFile(projectRootPath);
    //qDebug()<<QDir::currentPath();

    if(jsonFile.open(QIODevice::WriteOnly)){
        jsonFile.write(doc.toJson());
        jsonFile.close();
        qDebug()<<"PlayList.json已生成";
    }else{
        qDebug()<<"未生成"<<jsonFile.errorString();
    }
}

QString BGMList::getProjectRootPath()
{
    QString appDir=QCoreApplication::applicationDirPath();

    //qDebug()<<app;
    QDir dir(appDir);
    dir.cdUp();

    //qDebug()<<PRO_DIR;//$$PWD就是.pro文件的目录级别
    return PRO_DIR;

}

